//
// Created by yangchao on 2022/5/15.
// 145. 二叉树的后序遍历: https://leetcode.cn/problems/binary-tree-postorder-traversal/
//

#include "../DataStructure/TreeNode.h"
#include <vector>
#include <stack>
using namespace std;

class PostorderTraversal {
public:
    //迭代
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if (root == nullptr) return res;
        stack<TreeNode*> stk;
        stk.push(root);
        while (!stk.empty()) {
            TreeNode* node = stk.top();
            stk.pop();
            res.insert(res.begin(),node->val);
            if (node->left != nullptr) stk.push(node->left);
            if (node->right != nullptr) stk.push(node->right);
        }
        return res;
    }

    //递归
    vector<int> postorderTraversal2(TreeNode* root) {
        vector<int> res;
        postorder(root,res);
        return res;
    }

private:
    void postorder(TreeNode* root,vector<int>& res) {
        if (root == nullptr) return;
        postorder(root->left,res);
        postorder(root->right,res);
        res.push_back(root->val);
    }
};


